<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FormType } from './detail'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/collection'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  bannerPic: '',
  bottomPic: '',
  sharePic: '',
  shareTxt: '',
  getBtnPic: '',
  usedBtnPic: '',
  actStatus: 0,
})

const id = route.query.id as string

const rules = reactive({
  bannerPic: [
    { required: true, message: '请上传Banner图', trigger: 'blur' },
  ],
  bottomPic: [
    { required: true, message: '请上传底部图片', trigger: 'blur' },
  ],
  sharePic: [
    { required: true, message: '请上传分享图', trigger: 'blur' },
  ],
  shareTxt: [
    { required: true, message: '请输入分享语', trigger: 'blur' },
  ],
  getBtnPic: [
    { required: true, message: '请上传获取按钮图片', trigger: 'blur' },
  ],
  usedBtnPic: [
    { required: true, message: '请上传已使用按钮图片', trigger: 'blur' },
  ],
  actStatus: [
    { required: true, message: '请选择是否启用', trigger: 'blur' },
  ],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  // eslint-disable-next-line ts/ban-ts-comment
  // @ts-expect-error
  ruleForm.value[key] = url
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      // console.log(params)

      if (id) {
        // 编辑
        params.id = id
        PutModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'collectionIndex' })
          }
          else {
            ElMessage.error(`编辑失败。${res.errors}`)
          }
        })
      }
      else {
        // 添加
        PostCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.EmptyCollection()
            router.push({ name: 'collectionIndex' })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberCollection(newValue)
  }
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.GetCollection()
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="是否启用">
              <el-switch
                v-model="ruleForm.actStatus"
                :active-value="1"
                :inactive-value="-1"
                active-text="启用"
                inactive-text="未启用"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="分享语" prop="shareTxt">
              <el-input v-model="ruleForm.shareTxt" placeholder="请输入分享语" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="上传图片">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="分享图" prop="sharePic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.sharePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'sharePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="Banner图" prop="bannerPic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.bannerPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'bannerPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="底部图片" prop="bottomPic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.bottomPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'bottomPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="获取按钮图片" prop="getBtnPic">
              <ImageUpload
                width="auto" height="100" :size="5" :url="ruleForm.getBtnPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'getBtnPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="已使用按钮图片" prop="usedBtnPic">
              <ImageUpload
                width="auto" height="100" :size="5" :url="ruleForm.usedBtnPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'usedBtnPic')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
